<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\wxapp\controller;

use think\Db;
use cmf\controller\RestBaseController;
use wxapp\aes\WXBizDataCrypt;
use think\Validate;

class PublicController extends RestBaseController
{


    /**
     *Title:以后openid
     *<br/>By: 王龙 2022/8/29 15:51
     */
    public function getopenid(){

        $wxappSettings = cmf_get_option('wxapp_settings');

        $appId = $this->request->header('XX-Wxapp-AppId');

        if (empty($appId)) {
            if (empty($wxappSettings['default'])) {
                $this->error('没有设置默认小程序！');
            } else {
                $defaultWxapp = $wxappSettings['default'];
                $appid        = $defaultWxapp['app_id'];
                $key    = $defaultWxapp['app_secret'];
            }
        }

        $code=$this->request->param('code');

        $usrl="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$key."&js_code=".$code."&grant_type=authorization_code";

        $response = file_get_contents($usrl);


        $this->success('返回成功',json_decode($response));

    }

    /**
     * @return void
     */
    public function wxlogin(){

        $openid=$this->request->param('openid');
        $avatar=$this->request->param('avatar');
        $nickName=$this->request->param('nickName');
        $agentid=$this->request->param('agentid');



        $user=Db::name('user')->where(['openid'=>$openid])->find();

        if ($user){
            $instb['user_nickname']=$nickName;
            $instb['avatar']=$avatar;
            Db::name('user')->where(['openid'=>$openid])->update($instb);


            $token  = cmf_generate_user_token($user['id'], 'wxapp');


        }else{

            $ip          = $this->request->ip(0, true);

            $userId = Db::name("user")->insertGetId([
                'create_time'     => time(),
                'user_status'     => 1,
                'user_type'       => 2,
                'sex'             => 0,
                'user_nickname'   => $nickName,
                'avatar'          => $avatar,
                'balance'          => 0,
                'last_login_ip'   => $ip,
                'agentid' => $agentid,
            ]);

            $token = cmf_generate_user_token($userId, 'wxapp');
        }


        $user = Db::name('user')->where('id', $userId)->find();
        $this->success("登录成功!", ['token' => $token, 'user' => $user]);

    }

    /**
     * @return void
     * 获取电话
     */
    public function getmobile(){


        $code = $this->request->param('code');

        $set=Db::name('set')->where(['id'=>1])->find();

        $key=$set['secret'];
        $appid=$set['appid'];


        $content = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $key);

        $content=json_decode($content);

        $access_token=$content['access_token'];


        $url='https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;


        $data  = json_encode(['code'=>$code]);

        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);

        $ret= json_decode($output,true);
        $mobile=$ret['phone_info']['phoneNumber'];

        var_dump($mobile);

    }


    public function wxpay(){


        $appid='';
        $mch_id='';
        $nonce_str='';
        $zfmoney=1;
        $openid='';
        $key=''; //32位字符
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';



        $parameters = array(
            'appid' => $appid, //服务商ID
            'mch_id' => $mch_id, //商户号
            'nonce_str' => $nonce_str, //随机字符串
            'body' => '充值',
            'out_trade_no' => $nonce_str,
            'total_fee' => $zfmoney * 100, //分
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], //终端IP
            'notify_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/api.php/portal/index/payback',  //回调
            'openid' =>$openid, //用户id
            'trade_type' => 'JSAPI'//交易类型
        );



        //统一下单签名
        $parameters['sign'] = getSign($parameters, $key);
        $xmlData = arrayToXml($parameters);
        $return = xmlToArray(postXmlCurl($xmlData, $url, 60));
        $parameter = array(
            'appId' => $appid, //小程序ID
            'timeStamp' => '' . time() . '', //时间戳
            'nonceStr' => $nonce_str, //随机串
            'package' => 'prepay_id=' . $return['prepay_id'], //数据包
            'signType' => 'MD5'//签名方式
        );
        //签名
        $parameter['paySign'] = getSign($parameter, $key);


        $this->success('支付信息',$parameter);


    }


    // 微信小程序用户登录 TODO 增加最后登录信息记录,如 ip
    public function login()
    {
        $validate = new Validate([
            'code'           => 'require',
            'encrypted_data' => 'require',
            'iv'             => 'require',
            'raw_data'       => 'require',
            'signature'      => 'require',
        ]);

        $validate->message([
            'code.require'           => '缺少参数code!',
            'encrypted_data.require' => '缺少参数encrypted_data!',
            'iv.require'             => '缺少参数iv!',
            'raw_data.require'       => '缺少参数raw_data!',
            'signature.require'      => '缺少参数signature!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $code          = $data['code'];
        $wxappSettings = cmf_get_option('wxapp_settings');

        $appId = $this->request->header('XX-Wxapp-AppId');
        if (empty($appId)) {
            if (empty($wxappSettings['default'])) {
                $this->error('没有设置默认小程序！');
            } else {
                $defaultWxapp = $wxappSettings['default'];
                $appId        = $defaultWxapp['app_id'];
                $appSecret    = $defaultWxapp['app_secret'];
            }
        } else {
            if (empty($wxappSettings['wxapps'][$appId])) {
                $this->error('小程序设置不存在！');
            } else {
                $appId     = $wxappSettings['wxapps'][$appId]['app_id'];
                $appSecret = $wxappSettings['wxapps'][$appId]['app_secret'];
            }
        }


        $response = cmf_curl_get("https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code");

        $response = json_decode($response, true);
        if (!empty($response['errcode'])) {
            $this->error('操作失败!');
        }

        $openid     = $response['openid'];
        $sessionKey = $response['session_key'];

        $pc      = new WXBizDataCrypt($appId, $sessionKey);
        $errCode = $pc->decryptData($data['encrypted_data'], $data['iv'], $wxUserData);

        if ($errCode != 0) {
            $this->error('操作失败!');
        }

        $findThirdPartyUser = Db::name("third_party_user")
            ->where('openid', $openid)
            ->where('app_id', $appId)
            ->find();

        $currentTime = time();
        $ip          = $this->request->ip(0, true);

        $wxUserData['sessionKey'] = $sessionKey;
        unset($wxUserData['watermark']);

        if ($findThirdPartyUser) {
            $userId = $findThirdPartyUser['user_id'];
            $token  = cmf_generate_user_token($findThirdPartyUser['user_id'], 'wxapp');

            $userData = [
                'last_login_ip'   => $ip,
                'last_login_time' => $currentTime,
                'login_times'     => Db::raw('login_times+1'),
                'more'            => json_encode($wxUserData)
            ];

            if (isset($wxUserData['unionId'])) {
                $userData['union_id'] = $wxUserData['unionId'];
            }

            Db::name("third_party_user")
                ->where('openid', $openid)
                ->where('app_id', $appId)
                ->update($userData);

        } else {

            //TODO 使用事务做用户注册
            $userId = Db::name("user")->insertGetId([
                'create_time'     => $currentTime,
                'user_status'     => 1,
                'user_type'       => 2,
                'sex'             => $wxUserData['gender'],
                'user_nickname'   => $wxUserData['nickName'],
                'avatar'          => $wxUserData['avatarUrl'],
                'last_login_ip'   => $ip,
                'last_login_time' => $currentTime,
            ]);

            Db::name("third_party_user")->insert([
                'openid'          => $openid,
                'user_id'         => $userId,
                'third_party'     => 'wxapp',
                'app_id'          => $appId,
                'last_login_ip'   => $ip,
                'union_id'        => isset($wxUserData['unionId']) ? $wxUserData['unionId'] : '',
                'last_login_time' => $currentTime,
                'create_time'     => $currentTime,
                'login_times'     => 1,
                'status'          => 1,
                'more'            => json_encode($wxUserData)
            ]);

            $token = cmf_generate_user_token($userId, 'wxapp');

        }

        $user = Db::name('user')->where('id', $userId)->find();

        $this->success("登录成功!", ['token' => $token, 'user' => $user]);


    }



}
